package com.cloudm.technician.ui.base

import android.support.v7.widget.RecyclerView
import android.view.View
import com.cloudm.technician.extensions.logger
import com.cloudm.technician.ui.widget.OnceClickListener

/**
 * 作者: wesley
 * 时间: 2017/11/21
 * 描述: 基类适配器
 */
abstract class BaseAdapter<T> : RecyclerView.Adapter<BaseViewHolder<T>>() {

    val list: ArrayList<T> = arrayListOf()

    var onItemClickListener: OnItemClickListener<T>? = null

    fun clear() {
        list.clear()
    }

    fun addAllItems(listItem: ArrayList<T>) {
        list.addAll(listItem)
        notifyDataSetChanged()
    }

    fun removeItem(position: Int) {
        if (position >= 0 && list.size > position) {
            list.removeAt(position)
            notifyItemRemoved(position)
        }
    }

    override fun onBindViewHolder(holder: BaseViewHolder<T>, position: Int) {
        if (list.size <= position || list[position] == null) {
            logger(" list.size == ${list.size}, position == $position")
            return
        }
        holder.onBind(list[position])

        holder.itemView.setOnClickListener(object : OnceClickListener() {
            override fun onOnceClick(view: View) {
                val adapterPosition: Int = holder.adapterPosition
                if (list.size <= adapterPosition) {
                    logger(" list.size == ${list.size} adapterPosition == $adapterPosition")
                    return
                }
                onItemClickListener?.onItemClick(list[adapterPosition])
            }
        })
    }

    override fun getItemCount(): Int = list.size

    interface OnItemClickListener<in T> {
        fun onItemClick(t: T)
    }
}